﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Admin.Properties;
using SDT.Admin.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Linq;
using SDT.Lib.Helpers;

namespace SDT.Admin.Controllers
{
    /// <summary>
    /// Author: Takamaru Nguyen
    /// Date: 07/07/2010
    /// </summary>
	[RoleHelper(Roles = RoleSystem.Dictionary)]
    public class DemandCategoryController : Controller
    {
        ChoVietDataContext eDataContext = new ChoVietDataContext();
        //
        // GET: /DemandCategory/
        public ActionResult Index(int? page)
        {
            try
            {
                    if (page == null)
                        page = 1;
                    string order = UserState.getUserStateFromRequest("demandCategory.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("demandCategory.orderDir", "orderDir", "desc").ToString();
                    string keyword = UserState.getUserStateFromRequest("demandCategory.Keyword", "Keyword", "").ToString();
                    int currentDemandTypeID = Utils.ParseInt(UserState.getUserStateFromRequest("demandCategory.DemandType", "DemandTypeID", 0)); // Inserted by Vietlv(AddDate: 25/07/2011)
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("demandCategory.pageSize", "PageSize", 20).ToString());
                    string strPub = UserState.getUserStateFromRequest("demandCategory.CurrentPubStatus", "CurrentPubStatus", "").ToString();

                    int? CurrentPubStatus = null;
                    if (!string.IsNullOrEmpty(strPub))
                        CurrentPubStatus = Convert.ToInt32(strPub);

                    var categories = eDataContext.DemandCategories
                        .Where(e => currentDemandTypeID > 0 ? e.DemandTypeID == currentDemandTypeID : true) // Inserted by Vietlv(AddDate: 25/07/2011)
                        .Where(c => CurrentPubStatus.HasValue ? c.ActiveYN == (CurrentPubStatus.HasValue && CurrentPubStatus.Value == 1 ? true : false) : true)
                        .Where(c => (string.IsNullOrEmpty(keyword) ? true : c.Name.ToLower().Contains(keyword.ToLower().Trim())
                        ))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);
                    var listDemandTypes = eDataContext.DemandTypes.ToList();   // Inserted by Vietlv(AddDate: 25/07/2011)

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new DemandCategoryViewModels
                    {
                        Categories = categories,
                        CurrentPubStatus = CurrentPubStatus,
                        Keyword = keyword,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix,
                        DemandTypes = listDemandTypes,
                        currentDemandTypeID = currentDemandTypeID // Inserted by Vietlv(AddDate: 25/07/2011)
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /DemandCategory/Details/5

        public ActionResult Details(int id)
        {
            try
            {
                    DemandCategory proCat = eDataContext.DemandCategories.Where(c => c.ID == id).SingleOrDefault();
                    List<DemandCategory> categories = eDataContext.DemandCategories
                                                        .Where(c => c.ID != id)
                                                        .ToList();
                    var currentDemandType = eDataContext.DemandTypes.Where(e => e.ID == proCat.DemandTypeID).SingleOrDefault();
                    return View(new DemandCategoryInputModels
                    {
                        ListParentCategories = categories,
                        Category = proCat,
                        ID = id,
                        DemandType = currentDemandType
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View(new DemandCategoryInputModels
                {
                    ID = id
                });
            }
        }

        //
        // GET: /DemandCategory/Create
        public ActionResult Create()
        {
            try
            {
                    //List<DemandCategory> categories = eDataContext.DemandCategories.ToList();

                var listDemandTypes = eDataContext.DemandTypes.ToList(); // Inserted by Vietlv(AddDate: 25/07/2011)
                return View(new DemandCategoryInputModels {
                    DemandTypes = listDemandTypes
                });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        } 

        //
        // POST: /DemandCategory/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(DemandCategoryInputModels m)
        {
            try
            {
                    // TODO: Add insert logic here
                    UpdateModel(m);
                    m.Category.AddBy = UserManager.GetUserId();
                    m.Category.AddDate = DateTime.Now;
                    eDataContext.DemandCategories.InsertOnSubmit(m.Category);
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /DemandCategory/Edit/5
 
        public ActionResult Edit(int id)
        {
            try
            {
                    DemandCategory proCat = eDataContext.DemandCategories.Where(c => c.ID == id).SingleOrDefault();
                    //List<DemandCategory> categories = eDataContext.DemandCategories
                    //                                    .Where(c => c.ID != id)
                    //                                    .ToList();
                    var currentDemandType = eDataContext.DemandTypes.Where(e => e.ID == proCat.DemandTypeID).SingleOrDefault(); // Inserted by Vietlv(AddDate: 25/07/2011)
                    var listDemandTypes = eDataContext.DemandTypes.ToList(); // Inserted by Vietlv(AddDate: 25/07/2011)
                    return View(new DemandCategoryInputModels
                    {
                        Category = proCat,
                        currentDemandTypeID = currentDemandType.ID, // Inserted by Vietlv(AddDate: 25/07/2011)
                        DemandTypes = listDemandTypes               // Inserted by Vietlv(AddDate: 25/07/2011)
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /DemandCategory/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, DemandCategoryInputModels m)
        {
            try
            {
                    m.Category = eDataContext.DemandCategories.Where(c => c.ID == id).FirstOrDefault();
                    UpdateModel(m);
                    m.Category.ModifyBy = UserManager.GetUserId();
                    m.Category.ModifyDate = DateTime.Now;
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /DemandCategory/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                    DemandCategory dCat = eDataContext.DemandCategories.Where(d => d.ID == id).FirstOrDefault();
                    if (dCat == null)
                        throw new NullReferenceException();

                    return View(dCat);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /DemandCategory/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                    DemandCategory dCat = eDataContext.DemandCategories.Where(d => d.ID == id).FirstOrDefault();
                    eDataContext.DemandCategories.DeleteOnSubmit(dCat);
                    eDataContext.SubmitChanges();

                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
    }
}
